import "package:flutter/material.dart";
import "package:myapp/_common/UListTitle.dart";
import "package:myapp/_common/UseSliverAppBar.dart";
import "package:myapp/_views/home/widget/recommend/RecommendItemVideoItem.dart";
import 'dart:async';

class Arguments {
  RecommendItemVideoItem recommendItemVideoItem;
  Arguments({
    required this.recommendItemVideoItem,
  });
}

class NavigateBarItem extends StatelessWidget {
  final Widget child;
  final double padding;
  const NavigateBarItem({super.key, required this.child, this.padding = 12});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: padding),
      child: child,
    );
  }
}

/// 包含状态栏、导航栏（视频）、tab栏
class HeaderBar extends StatefulWidget {
  final double statusHeight;
  final List<VideoTabItem> tabs;
  final TabController tabController;
  final double navigateBarHeight;
  final double? tabHeight;
  final ScrollController scrollController; //滚动控制器，用于控制顶部导航栏和视频的状态
  final double expandedHeight; //展开高度
  final double collapsedHeight; //折叠高度
  final Function(int index, VideoTabItem tabItem)? onTabChanged;
  const HeaderBar({
    super.key,
    required this.statusHeight,
    required this.tabs,
    required this.tabController,
    required this.navigateBarHeight,
    this.tabHeight,
    this.onTabChanged,
    required this.scrollController,
    required this.expandedHeight,
    required this.collapsedHeight,
  });

  @override
  State<HeaderBar> createState() => _HeaderBarState();
}

class _HeaderBarState extends State<HeaderBar> {
  Color tabActiveColor = const Color(0xffFD6697);
  Color tabUnActiveColor = const Color.fromARGB(255, 79, 79, 79);
  bool useDanmu = true; //是否打开弹幕
  double maxScrollOffset = 0; //最大滚动偏移量
  double navigateBarThresholdRate = 0.3; //触发出现导航栏，并改变导航栏内容的阈值比例
  double navigateBarThresholdOffset = 0; //触发出现导航栏阈值高度
  Color navigateBarItemColor = Colors.white; //导航栏内容颜色，当

  double videoThresholdRate = 0.5; //触发显示视频的阈值比例
  double videoThresholdOffset = 0; //触发显示视频阈值高度

  /// 只有当视频处于暂停，并且滚动到阈值时，才会进入持续显示状态；
  /// 进入持续显示状态时，导航栏内容颜色会变成黑色，否则为白色
  /// 持续显示状态导航栏显示“继续播放”，否则显示“音效、小窗口、投屏”
  bool isContinuousShowNavigateBar = false;
  bool showVideoControlBar = false; //是否显示视频控制栏
  bool showNavigateBar = false; //是否显示导航栏
  bool tapVideoPlayer = false; //是否点击视频播放器
  bool showVideo = true; //是否显示视频
  bool removeVideo = false; //是否移除视频
  bool showControlBarShadow = false; //是否显示视频控制栏(导航栏)阴影

  late Timer? timer;

  @override
  void initState() {
    maxScrollOffset = widget.expandedHeight - widget.collapsedHeight;
    navigateBarThresholdOffset = maxScrollOffset * navigateBarThresholdRate;
    videoThresholdOffset = maxScrollOffset * videoThresholdRate;
    super.initState();
    widget.scrollController.addListener(() {
      var offset = widget.scrollController.offset;
      // 当滚动高度超过阈值，则显示持续导航栏
      if (offset > navigateBarThresholdOffset) {
        setState(() {
          isContinuousShowNavigateBar = true;
          navigateBarItemColor = Colors.black;
        });
        print('打开持续导航栏');
      } else {
        setState(() {
          isContinuousShowNavigateBar = false;
          navigateBarItemColor = Colors.white;
        });
        print('关闭持续导航栏');
      }
      if (offset > videoThresholdOffset) {
        setState(() {
          showVideo = false;
        });
        print('隐藏视频>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
      } else {
        setState(() {
          showVideo = true;
          if (removeVideo) removeVideo = false;
        });
        print('显示视频>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
      }
      print('滚动：$offset -- $maxScrollOffset');
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: double.infinity,
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: Container(
              color: Colors.orange,
              child: Stack(
                children: [
                  // 视频播放器
                  Positioned.fill(
                    child: AnimatedOpacity(
                      opacity: showVideo ? 1 : 0,
                      duration: const Duration(milliseconds: 500),
                      onEnd: () {
                        print('视频显示或隐藏动画结束');
                        setState(() {
                          removeVideo = !showVideo;
                        });
                      },
                      child: removeVideo
                          ? const SizedBox()
                          : GestureDetector(
                              onTap: () {
                                print('点击视频播放器');
                                if (!tapVideoPlayer) {
                                  setState(() {
                                    tapVideoPlayer = true;
                                    showVideoControlBar = true;
                                    showNavigateBar = true;
                                  });
                                  timer = Timer.periodic(
                                      const Duration(seconds: 3), (timer) {
                                    setState(() {
                                      tapVideoPlayer = false;
                                      showVideoControlBar = false;
                                      showNavigateBar = false;
                                    });
                                    timer.cancel();
                                  });
                                } else {
                                  setState(() {
                                    tapVideoPlayer = false;
                                    showVideoControlBar = false;
                                    showNavigateBar = false;
                                  });
                                  timer?.cancel();
                                }
                              },
                              child: Container(
                                color: const Color.fromARGB(131, 33, 149, 243),
                                height: double.infinity,
                                width: double.infinity,
                                child: const Center(child: Text('视频播放器')),
                              ),
                            ),
                    ),
                  ),
                  // 导航栏
                  AnimatedCrossFade(
                    firstChild: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6),
                      height: widget.navigateBarHeight,
                      child: UListTitle(
                        leading: Row(
                          children: [
                            NavigateBarItem(
                              child: Icon(
                                Icons.arrow_back_rounded,
                                color: navigateBarItemColor,
                              ),
                            ),
                            NavigateBarItem(
                              child: Icon(
                                Icons.home_outlined,
                                color: navigateBarItemColor,
                              ),
                            ),
                          ],
                        ),
                        content: Expanded(
                          child: isContinuousShowNavigateBar
                              ? NavigateBarItem(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.play_arrow_rounded,
                                        size: 32,
                                        color: navigateBarItemColor,
                                      ),
                                      Text(
                                        '继续播放',
                                        style: TextStyle(
                                          fontSize: 16,
                                          color: navigateBarItemColor,
                                        ),
                                      ),
                                    ],
                                  ),
                                )
                              : Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    NavigateBarItem(
                                      padding: 6,
                                      child: Icon(
                                        Icons.headset_mic_outlined,
                                        size: 20,
                                        color: navigateBarItemColor,
                                      ),
                                    ),
                                    NavigateBarItem(
                                      padding: 6,
                                      child: Icon(
                                        Icons.picture_in_picture_alt_rounded,
                                        size: 20,
                                        color: navigateBarItemColor,
                                      ),
                                    ),
                                    NavigateBarItem(
                                      padding: 6,
                                      child: Icon(
                                        Icons.cast_rounded,
                                        size: 20,
                                        color: navigateBarItemColor,
                                      ),
                                    ),
                                  ],
                                ),
                        ),
                        trailing: NavigateBarItem(
                          child: Icon(
                            Icons.more_vert_rounded,
                            color: navigateBarItemColor,
                          ),
                        ),
                      ),
                    ),
                    secondChild: const SizedBox.shrink(),
                    crossFadeState:
                        isContinuousShowNavigateBar || showNavigateBar
                            ? CrossFadeState.showFirst
                            : CrossFadeState.showSecond,
                    duration: const Duration(microseconds: 10),
                  ),
                ],
              ),
            ),
          ),
          Container(
            height: widget.tabHeight,
            color: Colors.white,
            child: Stack(
              alignment: Alignment.centerLeft,
              children: [
                Container(
                  margin: const EdgeInsets.only(left: 12),
                  width: 150,
                  child: TabBar(
                    isScrollable: false,
                    controller: widget.tabController,
                    tabs: widget.tabs.map((e) => Tab(text: e.name)).toList(),
                    indicatorColor: tabActiveColor,
                    labelColor: tabActiveColor,
                    unselectedLabelColor: tabUnActiveColor,
                    unselectedLabelStyle: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.normal,
                    ),
                    labelStyle: TextStyle(
                      fontWeight: FontWeight.normal,
                      fontSize: 14,
                      color: tabUnActiveColor,
                    ),
                    onTap: (index) {
                      widget.onTabChanged?.call(index, widget.tabs[index]);
                    },
                  ),
                ),
                Positioned(
                  right: 0,
                  top: 3,
                  bottom: 3,
                  child: Container(
                    margin: const EdgeInsets.only(right: 12, left: 12),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        width: 1,
                        color: Colors.black12,
                      ),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        AnimatedSize(
                          duration: const Duration(milliseconds: 150),
                          curve: Curves.linear,
                          child: Container(
                            width: useDanmu ? null : 0,
                            decoration: const BoxDecoration(
                              color: Color(0xffF4F6F6),
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(16),
                                bottomLeft: Radius.circular(16),
                              ),
                            ),
                            padding: const EdgeInsets.only(left: 10, right: 16),
                            child: const Align(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                '点我发弹幕',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.black38,
                                ),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              useDanmu = !useDanmu;
                              print('切换弹幕：$useDanmu');
                            });
                          },
                          child: Container(
                            width: 38,
                            padding: const EdgeInsets.only(right: 8, left: 8),
                            child: const Icon(
                              Icons.send_rounded,
                              size: 18,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class VideoTabItem {
  final String name;
  final String value;
  VideoTabItem({required this.name, required this.value});
}

class Video extends StatefulWidget {
  // 路由跳转传的参数
  final Arguments arguments;
  const Video({super.key, required this.arguments});
  @override
  State<StatefulWidget> createState() => _VideoState();
}

class _VideoState extends State<Video> with SingleTickerProviderStateMixin {
  late ScrollController controller;
  late TabController tabController;
  List<VideoTabItem> tabs = [
    VideoTabItem(name: '简介', value: '0'),
    VideoTabItem(name: '评论', value: '1'),
  ];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
    tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    double statusHeight = MediaQuery.of(context).padding.top; //状态栏高度
    final double videoHeaderHeight = screenWidth * 9 / 16; //视频高度
    const double tabHeight = 36; //tab高度
    const double navigateBarHeight = 56; //导航栏高度
    // 折叠 视频区域逐渐压缩，最后变成导航栏；展开则反过来
    // 展开高度
    final double expandedHeight = videoHeaderHeight + statusHeight + tabHeight;
    // 折叠高度
    double collapsedHeight = tabHeight + statusHeight + navigateBarHeight;
    return Scaffold(
      body: SizedBox(
        child: NestedScrollView(
          // floatHeaderSlivers: true,//控制顶部是否随着滑动滑动，false则必须到达顶部边缘才开始改变高度
          controller: controller,
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverOverlapAbsorber(
                handle:
                    NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                sliver: UseSliverAppBar(
                  scrollController: controller,
                  pinned: true,
                  expandedHeight: expandedHeight,
                  collapsedHeight: collapsedHeight,
                  child: HeaderBar(
                    statusHeight: statusHeight,
                    tabs: tabs,
                    tabController: tabController,
                    navigateBarHeight: navigateBarHeight,
                    tabHeight: tabHeight,
                    scrollController: controller,
                    expandedHeight: expandedHeight,
                    collapsedHeight: collapsedHeight,
                  ),
                ),
              ),
            ];
          },
          body: Builder(builder: (context) {
            return CustomScrollView(
              slivers: [
                SliverOverlapInjector(
                  handle:
                      NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                ),
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return ListTile(
                        title: Text('列表$index'),
                      );
                    },
                  ),
                )
              ],
            );
          }),
        ),
      ),
    );
  }
}
